package com.h5lib.xlsx4j;

import java.io.Closeable;
import java.io.IOException;

import org.xmlpull.v1.XmlSerializer;

public class XMLSheetWriter implements Closeable{

    private XmlSerializer outStream;
    private int rowNum=1;
    private XMLSharedStringWriter sharedStringWriter;
    
    public static final String[] COL_IDX = {
    	"A","B","C","D","E","F",
    	"G","H","I","J","K","J",
    	"M","N","O","P","Q","R",
    	"S","T","U","V","W","X","Y","Z"
    };
    
    
    
    public XMLSheetWriter(XmlSerializer newSerializer) {
    	outStream = newSerializer;
    	writeXmlStart();
    	
	}
    
    private void writeXmlStart() {
    	try {
			outStream.startDocument("UTF-8", true);
			outStream.startTag(null, "worksheet");
			outStream.attribute(null, "xmlns", "http://schemas.openxmlformats.org/spreadsheetml/2006/main");
			outStream.attribute(null, "xmlns:r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
			outStream.attribute(null, "xmlns:mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
			outStream.attribute(null, "mc:Ignorable", "x14ac");
			outStream.attribute(null, "xmlns:x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac");
			outStream.startTag(null, "sheetData");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
    
    private void writeXmlEnd() {
    	try {
    		outStream.endTag(null, "sheetData");
			outStream.endTag(null, "worksheet");
			outStream.endDocument();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void addXLSXSheetRow(XLSXSheetRow row){
    	try {
			outStream.startTag(null, "row");
			outStream.attribute(null, "r", rowNum+"");
			int size = row.size();
			for(int i=0 ; i<size;i++){
				outStream.startTag(null, "c");
				outStream.attribute(null, "r", COL_IDX[i]+rowNum);
				outStream.attribute(null, "t", "s");
				outStream.startTag(null, "v");
				outStream.text(sharedStringWriter.getIndex()+"");
				sharedStringWriter.addSharedString(row.get(i));
				outStream.endTag(null, "v");
				outStream.endTag(null, "c");
			}
			outStream.endTag(null, "row");
		} catch (Exception e) {
			e.printStackTrace();
		}
    	rowNum++;
    }
	
	@Override
	public void close() throws IOException {
		writeXmlEnd();
	}

	public XMLSharedStringWriter getSharedStringWriter() {
		return sharedStringWriter;
	}

	public void setSharedStringWriter(XMLSharedStringWriter sharedStringWriter) {
		this.sharedStringWriter = sharedStringWriter;
	}
 
}
